<?php namespace App\Http\Services;

use App\FollowIntegral;
use App\UserAuth;
use App\Userinfo;
use App\WxAuth;
use Auth;
use Blocktrail\CryptoJSAES\CryptoJSAES;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Cookie;
use App\User;

class UserManager
{
    public static function isLogin(Request $request = null,$front = 0)
    {
        if (!isset($_COOKIE['user_token'])) {
            if (is_null($request)) {
                return false;
            } else {
                $token = !is_null($request->header('User-token')) ? $request->header('User-token') : $request->get('user_token');
                if (!is_null($token)) {

                    $openid = false;
                    try {
                        $openid = CryptoJSAES::decrypt(str_replace(" ", "+", $token), env("AES_KEY"));
                    } catch (\Exception $e) {
                        return false;
                    }

                    if (!$openid)
                        return false;

                    $thatUser = User::whereWxOpenid($openid)->first();
                    if (!$thatUser){
                        $thatUser = User::whereUserKey($openid)->first();
                        if(!$thatUser){
                            return false;
                        }
                    }

                    return $thatUser;
                } else {
                    return false;
                }
            }
        } else {
            $token = Cookie::get('user_token');

            if (!$token || is_null($token) || $token == '' || $front == 0){
                $token = !is_null($request->header('User-token')) ? $request->header('User-token') : $request->get('user_token');
            }

            if (!$token || is_null($token))
                return false;

            $openid = false;
            try {
                $openid = CryptoJSAES::decrypt(str_replace(" ", "+", $token), env("AES_KEY"));
            } catch (\Exception $e) {
                return false;
            }

            if (!$openid)
                return false;

            $thatUser = User::whereWxOpenid($openid)->first();
            if (!$thatUser){
                $thatUser = User::whereUserKey($openid)->first();
                if(!$thatUser){
                    return false;
                }
            }

            return $thatUser;
        }
    }

    public static function addIntegral(User $user,$type){
        //获取当天的最大时间和最小时间
        $ty = date('Y', time());
        $tm = date('m', time());
        $td = date('d', time());
        $todayStartTime = mktime(0,0,0,$tm,$td,$ty);
        $todayEndTime   = mktime(23,59,59,$tm,$td,$ty);

        switch ($type){
            case "daka":
                $newIntegral = new FollowIntegral();
                $newIntegral->user_id = $user->id;
                $newIntegral->integral = 10;
                $newIntegral->type     = "like";
                $newIntegral->save();

                $thatUserInfo = Userinfo::whereUserId($user->id)->first();
                if($thatUserInfo){
                    $thatUserInfo->integral = (int)$thatUserInfo->integral + 10;
                    $thatUserInfo->save();
                }
                break;
           case "like":
                $mySum = FollowIntegral::whereUserId($user->id)->whereType("like")->whereBetween("created_at",[date('Y-m-d H:i:s',$todayStartTime),date('Y-m-d H:i:s',$todayEndTime)])->sum('integral');
                if($mySum < 10){
                    $newIntegral = new FollowIntegral();
                    $newIntegral->user_id = $user->id;
                    $newIntegral->integral = 1;
                    $newIntegral->type     = "like";
                    $newIntegral->save();

                    $thatUserInfo = Userinfo::whereUserId($user->id)->first();
                    if($thatUserInfo){
                        $thatUserInfo->integral = (int)$thatUserInfo->integral + 1;
                        $thatUserInfo->save();
                    }
                }
                break;
            case "comment":
                $mySum = FollowIntegral::whereUserId($user->id)->whereType("comment")->whereBetween("created_at",[date('Y-m-d H:i:s',$todayStartTime),date('Y-m-d H:i:s',$todayEndTime)])->sum('integral');
                if($mySum < 10){
                    $newIntegral = new FollowIntegral();
                    $newIntegral->user_id = $user->id;
                    $newIntegral->integral = 2;
                    $newIntegral->type     = "comment";
                    $newIntegral->save();

                    $thatUserInfo = Userinfo::whereUserId($user->id)->first();
                    if($thatUserInfo){
                        $thatUserInfo->integral = (int)$thatUserInfo->integral + 2;
                        $thatUserInfo->save();
                    }
                }
                break;
        }

        return true;
    }

    public static function buildRzKey($user_id = 0)
    {
        $num = mt_rand(1000, 9999);
        $rzKey = md5($user_id . time() . $num);
        return $rzKey;
    }

    public static function signUp($phone, $password)
    {
        $user = new User();
        $user->phone = $phone;
        $user->password = bcrypt($password);
        $user->status = 0;
        $user->save();

        $user->user_key = self::buildRzKey($user->id);
        $user->save();

        return $user;
    }

    /**
     * 检查用户名是否已经存在或被使用
     * @param $username
     * @return bool
     */
    public static function isUsernameExists($username){
        if(User::whereUsername($username)->exists())
            return true;
        return false;
    }

    /**
     * 通过用户名来登录
     * @param $username
     * @param $password
     * @param bool $remeber
     */
    public static function signInByUsername($username, $password, $remember = false){
        if(!self::isUsernameExists($username))
            return false;

        if(Auth::attempt(['username' => $username, 'password' => $password],$remember)){
            return Auth::user();
        }

        return false;
    }
}
